var piStore;
var piGrid;
var piWindow;
var sm;
var ctCollarType = new i18nMessage('../../servlet/CodeTableServlet?name=CtCollarType');
var ctSeasonNumber = new i18nMessage('../../servlet/CodeTableServlet?name=CtSeasonNumber');
var ctVersion = new i18nMessage('../../servlet/CodeTableServlet?name=CtVersion');
var ctProductFamily = new i18nMessage('../../servlet/CodeTableServlet?name=CtProductFamily');
var ctDesignType = new i18nMessage('../../servlet/CodeTableServlet?name=CtDesignType');
var selectedRecords = new Array();
var selectedIds = new Array();

var selectProductIdentification = function(selectCallback){
    if (!piWindow) {
        piWindow = new Ext.Window({
            title: message.get('message.combo.pleaseselect'),
            layout: 'fit',
            width: 960,
            height: 605,
            closeAction: 'hide',
            plain: true,
            modal: true,
            items: [{
                id: 'buttonPanel',
                region: 'center',
                bodyStyle: {
                    background: '#ffffff',
                    padding: '7px'
                },
                html: '<div id="piDiv"></div>'
            }]
        });
		
		piWindow.on(
			'beforehide',
			function(){
				selectProductIdentificationCallBack(selectedIds, selectedRecords);
			}
		);
		
    }
    piWindow.show();
    
    if (piGrid) 
        return;
    piStore =  new Ext.data.Store({
                    url: '../../servlet/ProductIdentificationServlet?action=4',
        reader: new Ext.data.XmlReader({
            record: 'item',
            id: 'id',
            totalRecords: 'itemTotal'
        }, [ 
        'index', 'id', 'ctProductFamily', 'biMeasureSpecificationId',
		'ctMachineType', 'type', 'orderNumber',
		 'yarnNumber', 'dhlNumber', 'ctDesignType',
		 'style', 'customerLinkman', 'model', 
		 'ctSeasonNumber', 'createDate', 'reference',
		 'ctVersion', 'patronageNumer', 'front', 
		 'back', 'sleeves', 'bottomThrum', 
		 'sleevesThrum', 'necklineThrum', 'needle', 
		 'weight', 'comment', 'photoName', 'frontPhotoName','backPhotoName','otherPhotoName',
		 'chartName', 'modifyDate', 
		 'isSimilary', 'isNewfashioned', 'isDifficulty', 
		 'dhlNumber', {name: 'biFranceCustomer.name', mapping: 'customerName'},
		 {name: 'biFranceCustomer.department', mapping: 'customerDepartment'},
		 'isTagged','isYarned', 'isOrdered', 'isButtoned', 'isZipped', 'isAo', 'isAddtoProcurement', 'isAddtoPackage']),
        
        remoteSort: true
    });
	
	piStore.on(
		'load',
		function(store, records, options){
			for(var i = 0; i < records.length; i ++){
				if(selectedIds.indexOf(records[i].data.id) != -1){
					sm.selectRow(i);
				}
			}
		}
	);
    
    piStore.setDefaultSort('id', 'desc');
	
	var piFilters = new Ext.grid.GridFilters({
		  filters:[
			{type: 'list',  dataIndex: 'ctSeasonNumber', options: ctSeasonNumber.getCtArray() },
			{type: 'list',  dataIndex: 'ctProductFamily', options: ctProductFamily.getCtArray() },
			{type: 'list',  dataIndex: 'ctDesignType', options: ctDesignType.getCtArray() },
			{type: 'string',  dataIndex: 'biFranceCustomer.name'},
			{type: 'string',  dataIndex: 'biFranceCustomer.department'},
			{type: 'string',  dataIndex: 'model'},
			{type: 'string',  dataIndex: 'reference'},
			{type: 'string',  dataIndex: 'style'},
			{type: 'date',  dataIndex: 'createDate'},
			{type: 'date',  dataIndex: 'modifyDate'},
			{type: 'list',  dataIndex: 'ctVersion',options: ctVersion.getCtArray()},
			{type: 'string',  dataIndex: 'patronageNumer'}
	]});
	
	var piExpander = new Ext.grid.RowExpander({
	    tpl : new Ext.Template(
			'<p><b>' + piMessage.get('ui.productidentification.ordernumber') + ':</b> {orderNumber} &nbsp;&nbsp;&nbsp;&nbsp;<b>' + piMessage.get('ui.productidentification.dhl') + ':</b> {dhlNumber} &nbsp;&nbsp;&nbsp;&nbsp;</p><br/>',
	        '<p><b>' + referenceMessage.get('ui.reference.front') + ':</b> {front} &nbsp;&nbsp;&nbsp;&nbsp; <b>' + referenceMessage.get('ui.reference.back') + ':</b> {back}&nbsp;&nbsp;&nbsp;&nbsp;',
			'<b>' + referenceMessage.get('ui.reference.sleeves') + ':</b> {sleeves} &nbsp;&nbsp;&nbsp;&nbsp; <b>' + referenceMessage.get('ui.reference.bottomthrum') + ':</b> {bottomThrum}&nbsp;&nbsp;&nbsp;&nbsp;',
			'<b>' + referenceMessage.get('ui.reference.sleevesthrum') + ':</b> {sleevesThrum} &nbsp;&nbsp;&nbsp;&nbsp; <b>' + referenceMessage.get('ui.reference.necklinethrum') + ':</b> {necklineThrum}&nbsp;&nbsp;&nbsp;&nbsp;</p><br/>',
	        '<p><b>' + referenceMessage.get('ui.reference.needle') + ':</b> {needle} &nbsp;&nbsp;&nbsp;&nbsp; <b>' + referenceMessage.get('ui.reference.machinetype') + ':</b> {ctMachineType}&nbsp;&nbsp;&nbsp;&nbsp;',
			'<b>' + referenceMessage.get('ui.reference.weight') + ':</b> {weight} &nbsp;&nbsp;&nbsp;&nbsp; <b>' + piMessage.get('ui.productidentification.yarnnumber') + ':</b> {yarnNumber}&nbsp;&nbsp;&nbsp;&nbsp;',
			'</p><br/>',
			'<p><img src="../../_temp/{chartName}" width="150px"/> &nbsp;&nbsp;&nbsp;&nbsp;<img src="../../_temp/{photoName}" width="150px"/>',
			//'&nbsp;&nbsp;&nbsp;&nbsp;<img src="../../_temp/{frontPhotoName}" width="150px"/>&nbsp;&nbsp;&nbsp;&nbsp;<img src="../../_temp/{backPhotoName}" width="150px"/>&nbsp;&nbsp;&nbsp;&nbsp;<img src="../../_temp/{otherPhotoName}" width="150px"/></p><br/>',
			'<p><b>' + piMessage.get('ui.productidentification.comment') + ':</b> {comment}</p><br/>'
	    )
	});

	sm = new Ext.grid.CheckboxSelectionModel();
	sm.on(
		'rowselect',
		function(thisSM, rowIndex, record){
			if(selectedIds.indexOf(record.data.id) == -1){
				selectedIds[selectedIds.length] = record.data.id;
				selectedRecords[selectedRecords.length] = '(' + record.data.ctSeasonNumber + ', ' + record.data['reference'] + ', ' + record.data['patronageNumer'] + ', ' + record.data.orderNumber + ')';
			}
		}
	);
	
	sm.on(
		'rowdeselect',
		function(thisSM, rowIndex, record){
			selectedIds.remove(record.data.id);
			selectedRecords.remove('(' + record.data.seasonNumber + ', ' + record.data['biReference.reference'] + ', ' + record.data.orderNumber + ')');
		}
	);
    // create the grid
    piGrid = new Ext.grid.GridPanel({
        title: piMessage.get('ui.productidentification.listtitle'),
        store: piStore,
        stripeRows: true,
        plugins: [piFilters,piExpander],
        height: 560,
		sm: sm,
        columns: [piExpander,sm,{
			header: piMessage.get('ui.productidentification.isaddprocurement'),
			width: 50,
			dataIndex: 'isAddtoProcurement',
			renderer: isAddtoProcurement
		},{
			header: piMessage.get('ui.productidentification.isaddpackage'),
			width: 50,
			dataIndex: 'isAddtoPackage',
			renderer: isAddtoPackage
		},{
            header: message.get('message.list.id'),
            width: 50,
            dataIndex: 'index',
            sortable: false
        },{
            header: fcMessage.get('ui.francecustomer.name'),
            dataIndex: 'biFranceCustomer.name',
            sortable: true
        }, {
            header: fcMessage.get('ui.francecustomer.department'),
            dataIndex: 'biFranceCustomer.department',
            sortable: true
        },{
            header: piMessage.get('ui.productidentification.style'),
            dataIndex: 'style',
            sortable: true
        },{
            header: message.get('message.edit.productfamily'),
            dataIndex: 'ctProductFamily',
            sortable: true
        },{
            header: piMessage.get('ui.productidentification.designtype'),
            dataIndex: 'ctDesignType',
            sortable: true
        },{
            header: referenceMessage.get('ui.reference.reference'),
            dataIndex: 'reference',
            sortable: true
        },{
            header: piMessage.get('ui.productidentification.seasonnumber'),
            dataIndex: 'ctSeasonNumber',
            sortable: true
        },{
            header: piMessage.get('ui.productidentification.model'),
            dataIndex: 'model',
            sortable: true
        },{
            header: piMessage.get('ui.productidentification.chartversion'),
            dataIndex: 'ctVersion',
            sortable: true
        },{
            header: piMessage.get('ui.productidentification.patronagenumer'),
            dataIndex: 'patronageNumer',
            sortable: true
        },{
            header: message.get('message.edit.createdate'),
            dataIndex: 'createDate',
            sortable: true
        },{
            header: message.get('message.edit.modifydate'),
            dataIndex: 'modifyDate',
            sortable: true
        }],
        viewConfig: {
            forceFit: true
        },
        loadMask: true,
        renderTo: 'piDiv',
        bbar: new Ext.PagingToolbar({
            pageSize: 20,
            store: piStore,
            displayInfo: true
        })
    });
    
    var startPage = getPrarmeterValue(window.location, 'startPage');
    var start;
    if (startPage == null || startPage == '') {
        start = 0;
    }
    else {
        start = (startPage - 1) * 20;
    }
    piStore.load({
        params: {
            start: start,
            limit: 20
        }
    });
	
	function isAddtoProcurement(value, p, record){
		if(value == '0')
			return String.format('<img ext:qtip="{0}" src="../../images/icons/cross.png" />', message.get('message.list.no'));
		else
			return String.format('<img ext:qtip="{0}" src="../../images/icons/tick.png"/>', message.get('message.list.yes'));
    }
	
	function isAddtoPackage(value, p, record){
		if(value == '0')
			return String.format('<img ext:qtip="{0}" src="../../images/icons/cross.png" />', message.get('message.list.no'));
		else
			return String.format('<img ext:qtip="{0}" src="../../images/icons/tick.png"/>', message.get('message.list.yes'));
    }
}

